package utils;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class StringUtils {

    public static String toHexByteStr(String str,Charset charset){
        StringBuilder builder = new StringBuilder();

        try{
            byte[] gbkStr = str.getBytes(charset);
            for (byte s:gbkStr){
                builder.append(Integer.toHexString(s & 0xFF));
                builder.append(" ");
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return builder.toString();
    }

    /**
     * 根据长度进行切割，并替换为空格
     * @param chunkLen 多长作为一组
     * @return
     */
    public static String chunkedByEmpty(final String str,final int chunkLen){

        if (str == null||chunkLen<= 0){
            return str;
        }

        StringBuilder builder = new StringBuilder();
        char[] array = str.toCharArray();
        for (int i = 0;i<array.length;i++){
            builder.append(array[i]);
            if (((i+1)%chunkLen) == 0){
                builder.append(" ");
            }
        }

        return builder.toString();
    }

    /**
     * 根据长度切割（如果每两个作为一个元素），如："HelloWorld"，切割为5，则返回String{Hello,World}
     * @param chunkLen 多长作为一组
     * @return
     */
    public static List<String> chunked(final String str,final int chunkLen){

        if (str == null||chunkLen<= 0){
            return null;
        }

        StringBuilder builder = new StringBuilder();
        List<String> list = new ArrayList<>();

        char[] array = str.toCharArray();

        for (int i = 0;i<array.length;i++){
            builder.append(array[i]);
            if (((i+1)%chunkLen) == 0){
                list.add(builder.toString());
                builder.setLength(0);
            }
        }

        return list;
    }

    public static String formatProtocol(String input) throws Exception {

        input = input.trim()
                .replaceAll("\r|\n|0x","")//移除换行符及0x字符
                .replaceAll("\\s+", " ");//存在连续多个空格则仅保留一个空格

        if (!input.contains(" ")){
            if (input.length()%2 == 0){
                input = StringUtils.chunkedByEmpty(input,2);
            }else{
                throw new Exception("数据长度为奇数，且找不到空格，请检查数据是否正常");
            }
        }

        return input;
    }
}
